package com.ljx.NoteBody.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ljx.NoteBody.common.MyException;
import com.ljx.NoteBody.utils.TokenUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            throw new MyException("token不能为空");
        }
        try {
            TokenUtil.verify(token);
        } catch (SignatureVerificationException e) {
            throw new MyException("无效签名！ 错误 ->" + e);
        } catch (TokenExpiredException e) {
            throw new MyException("token过期！ 错误 ->" + e);
        } catch (AlgorithmMismatchException e) {
            throw new MyException("token算法不一致！ 错误 ->" + e);
        } catch (Exception e) {
            throw new MyException("token无效！ 错误 ->" + e);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
